package ink.ykb.droolstest.config;

import java.io.IOException;
import org.beetl.core.Template;
import org.beetl.sql.core.JavaType;
import org.beetl.sql.core.db.ColDesc;
import org.beetl.sql.core.db.TableDesc;
import org.beetl.sql.core.kit.GenKit;
import org.beetl.sql.ext.gen.CodeGen;
import org.beetl.sql.ext.gen.GenConfig;
import org.beetl.sql.ext.gen.SourceGen;

public class MyMapperCodeGen implements CodeGen {
  String pkg = null;

  public MyMapperCodeGen() {
      mapperTemplate = new GenConfig().getTemplate("/gen/mapper.btl");

  }

  public MyMapperCodeGen(String pkg) {
      this();
      this.pkg = pkg;
  }

  private String mapperTemplate = "";

  public String getMapperTemplate() {
      return mapperTemplate;
  }

  public void setMapperTemplate(String mapperTemplate) {
      this.mapperTemplate = mapperTemplate;
  }

  @Override
  public void genCode(String entityPkg, String entityClass, TableDesc tableDesc, GenConfig config,
          boolean isDisplay) {
      if (pkg == null) {
          pkg = entityPkg;
      }
      Template template = SourceGen.getGt().getTemplate(mapperTemplate);
      String mapperClass = entityClass + "Dao";
      template.binding("className", mapperClass);
      template.binding("package", pkg);
      template.binding("entityClass", entityClass);
      if(tableDesc.getIdNames() != null && tableDesc.getIdNames().size() > 0) {
        
        String key = (String)(tableDesc.getIdNames().toArray())[0];
        
        ColDesc desc = tableDesc.getColDesc(key);
        String keyType = JavaType.getType(desc.sqlType, desc.size, desc.digit);
        if(config.isPreferBigDecimal()&&keyType.equals("Double")){
          keyType = "BigDecimal";
        }       
        if(config.isPreferDate()&&keyType.equals("Timestamp")){
          keyType ="Date";
        }
        
        template.binding("keyType", keyType);
      }
      

//      String mapperHead = "import " + entityPkg + ".*;" + SourceGen.CR;
//      template.binding("imports", mapperHead);
      String mapperCode = template.render();
      if (isDisplay) {
          System.out.println(mapperCode);
      } else {
          try {
              SourceGen.saveSourceFile(GenKit.getJavaSRCPath(), pkg, mapperClass, mapperCode);
          } catch (IOException e) {
              throw new RuntimeException("mapper代码生成失败", e);
          }
      }

  }

}
